package wrapper

import (
	"gitee.com/ymofen/gobase"
	"sync/atomic"
	"time"
)

type LocalStorage struct {
	filename string
	sto      *SuperValue
}

var (
	localstorage_createflag int32 = 0
	localstorage            *LocalStorage
)

func NewLocalStorage(filename string) *LocalStorage {
	rval := &LocalStorage{filename: filename}
	rval.Reload()
	return rval
}

func DefaultLocalStorage() *LocalStorage {
	if localstorage == nil {
		if atomic.CompareAndSwapInt32(&localstorage_createflag, 0, 1) {
			localstorage = NewLocalStorage("app.localstorage")
		} else {
			time.Sleep(time.Millisecond * 100)
		}
	}
	return localstorage
}

func (this *LocalStorage) Reload() error {
	if gobase.FileIsExists(this.filename) {
		sto, e1 := NewSVFromFile(this.filename)
		if e1 != nil {
			return e1
		}
		this.sto = sto
	} else {
		this.sto = NewSVObject()
	}
	return nil
}

func (this *LocalStorage) Flush() error {
	return this.sto.SaveFile2(this.filename, true, false)
}

func (this *LocalStorage) SetValues(kv ...interface{}) {
	this.sto.SetKeyValues(kv...)
}

func (this *LocalStorage) StringBy(k string, def string) string {
	return this.sto.StringByName(k, def)
}
